package com.test.personalblogproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.personalblogproject.mapper.ArticleBodyMapper;
import com.test.personalblogproject.mapper.ArticleMapper;
import com.test.personalblogproject.mapper.ArticleTagMapper;
import com.test.personalblogproject.mapper.UserMapper;
import com.test.personalblogproject.pojo.*;
import com.test.personalblogproject.service.ArticleService;
import com.test.personalblogproject.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper,Article> implements ArticleService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Override
    @Transactional
    public Result publish(ArticleParam articleParam) {
        //获取当前用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User sysUser = userMapper.findByUserName(username);
        //创建文章
        Article article = new Article();
        article.setAuthorId(Long.valueOf(sysUser.getId()));
        article.setCategoryId(Long.valueOf(articleParam.getCategory().getId()));
        article.setCreateDate(System.currentTimeMillis());
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        //默认0
        article.setViewCounts(0);
        //默认普通文章
        article.setWeight(Article.Article_Common);
        //默认没有bodyId
        article.setBodyId(-1L);
        //插入数据库
//        this.articleMapper.insert(article);
        this.articleMapper.insert(article);
        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBody.setArticleId(article.getId());
        articleBodyMapper.insert(articleBody);
        //更新article


        article.setBodyId(articleBody.getId());
        articleMapper.updatebodyId(article.getId(), articleBody.getId());



        //tags
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(tag.getId());
                this.articleTagMapper.insert(articleTag);
            }
        }

        //articleMapper.updateById(article);
        //返回文章id
        Article articleVo = new Article();
        articleVo.setId(article.getId());
        //return Result.success("id:"+articleVo.getId());
        Map<String, Object> data = new HashMap<>();
        data.put("id", article.getId());

        return new Result<>(200, "success", data);   // 新
    }

    @Override
    public Result FindArticlesByAuthorId(Long authorId) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<Article>().eq(Article::getAuthorId, authorId);
        List<Article> articleList=list(queryWrapper);
        List<ArticleVo> articleVoList=copyList(articleList);
        return Result.success(articleVoList);


    }
    List<ArticleVo> copyList(List<Article> articles){
        List<ArticleVo> articleVoList=new ArrayList<>();
        for(Article article:articles){
            articleVoList.add(copy(article));

        }
        return articleVoList;
    }
    ArticleVo copy(Article article){
        ArticleVo articleVo=new ArticleVo();
        BeanUtils.copyProperties(article,articleVo);
        Long authorId=article.getAuthorId();
        articleVo.setAuthor(userMapper.selectById(authorId).getUserPic());
        return articleVo;
    }

    @Override
    public Result deleteById(Long id) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User sysUser = userMapper.findByUserName(username);
        Integer sysUserId=sysUser.getId();
        Article article=articleMapper.selectById(id);
        Long authorId=article.getAuthorId();
        if(authorId != null && authorId.longValue() == sysUserId.longValue()) {
           if(this.articleMapper.deleteById(id))
               return Result.success("删除成功");
           else  return Result.error("删除失败");

        }
        return Result.error("没有权限");


    }

    @Override
    public Object updateByarticleId(ArticleParam articleParam) {


        Article pre_article=getById(articleParam.getId());

        Long articleId=pre_article.getId();
        Long authorId=pre_article.getAuthorId();

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User sysUser = userMapper.findByUserName(username);
        Long currentAuthorId=Long.valueOf(sysUser.getId());
        if(!currentAuthorId.equals(authorId)) return Result.error("没有权限");

        //修改article表里的东西
        Article article=new Article();
        article.setId(articleParam.getId());
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCategoryId(Long.valueOf(articleParam.getCategory().getId()));
        boolean a1=updateById(article);
        //修改内容

        boolean a2=true;
            ArticleBody articleBody=new ArticleBody();
            articleBody.setId(pre_article.getBodyId());
            articleBody.setContent(articleParam.getBody().getContent());
            articleBody.setContentHtml(articleParam.getBody().getContentHtml());
            articleBody.setArticleId(articleParam.getId());
          a2=articleBodyMapper.updateById(articleBody)!=0;

        boolean a3=true;
        if(articleParam.getTags()!=null){
            //删除标签
            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            articleTagLambdaQueryWrapper.eq(ArticleTag::getArticleId,articleParam.getId());
            articleTagMapper.delete(articleTagLambdaQueryWrapper);

            List<ArticleTag> newTags = articleParam.getTags().stream()
                    .map(tagVo -> {
                        ArticleTag articleTag = new ArticleTag();
                        articleTag.setArticleId(articleParam.getId());
                        articleTag.setTagId(tagVo.getId());
                        return articleTag;
                    })
                    .collect(Collectors.toList());

            a3=insertlist(newTags);
        }

        return Result.success(a1&&a2&&a3);

        }
        boolean insertlist(List<ArticleTag> list){
        boolean r=true;
        for (ArticleTag articleTag:list){
            boolean a=articleTagMapper.insert(articleTag)==0;
            if(a) r=false;
        }
        return r;


    }

    @Override
    public void like(ArticleParam articleParam) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userMapper.findByUserName(username);
    }

    /** 点赞/取消点赞二合一：返回最新状态 true=已赞 */
    @Override
    public boolean toggleLike(int userId, Long articleId) {
        int rc = articleMapper.insert1(userId, articleId);
        if (rc == 0) {   // 已存在 -> 取消
            articleMapper.delete(userId, articleId);
            return false;
        }
        return true;
    }

    @Override
    public List<Integer> likedArticleIds( int userId) {
        return articleMapper.selectArticleIdsByUser(userId);
    }

    @Override
    public int countLikes(int articleId) {
        return articleMapper.countLikes(articleId);
    }
}
